package middleware

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"good.house/internal/repository"
	"good.house/internal/utils"
	"good.house/pkg/response"
)

func AuthMiddleware(repo repository.IUserRepository) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.GetHeader("Authorization")
		if tokenString == "" {
			ctx.JSON(401, gin.H{"error": "未提供token"})
			ctx.Abort()
			return
		}

		cfg := utils.GetConfigByGinContext(ctx)

		if cfg == nil {
			response.Error(ctx, "内部错误")
			ctx.Abort()
			return
		}

		// 验证 token
		token, err := utils.ValidateToken(tokenString, cfg.JWt.SecretKey)
		if err != nil {
			response.AuthError(ctx, "无效的token")
			ctx.Abort()
			return
		}

		// 获取 claims
		claims, ok := token.Claims.(jwt.MapClaims)

		if !ok {
			response.AuthError(ctx, "无效的token")
		}

		userId := int64(claims["id"].(float64))

		// 将用户信息存储到 context
		ctx.Set("userID", userId)
		ctx.Set("username", claims["username"])

		id := fmt.Sprintf("%d", userId)
		exists := repo.HasTokenId(id)

		if !exists {
			response.AuthError(ctx, "无效的token")
			ctx.Abort()
			return
		}

		// 更新redistoken的时间
		repo.SetTokenId(id)

		ctx.Next()
	}
}
